package com.bjdd.jdy.ui.signScan;

import com.baidu.location.BDLocation;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.bjdd.jdy.Constant;
import com.bjdd.jdy.baidu.LocationUtils;
import com.bjdd.jdy.util.JumpUtil;
import com.bjdd.jdy.util.L;
import com.bjdd.jdy.util.SpUtil;
import com.bjdd.jdy.util.T;

/**
 * Created by Administrator on 2017/5/8.
 */

public class SignScanPresenter extends SignScanContract.Presenter{
    private double lat,lng;
    @Override
    public void onStart() {
        rxManager.on(Constant.EVENT_LOCATION_ONCE, msg -> locationBack((BDLocation) msg));
        if (SpUtil.getUser() == null || SpUtil.getUser().equals("") || SpUtil.getUser().getCarrierId() == null) {
            JumpUtil.toLogin(context);
            return;
        }
    }

    @Override
    void getQrCode(String orderId) {
        showLoadingDialog(false);
        String token = SpUtil.getToken();
        rxManager.add(model.getCodeData(token,orderId).subscribe(result -> {
            hideLoadingDialog();
            if (!result.isError()){
                view.codeBack(result.getData());
            }else {
                T.show(result.getMsg());
            }
        },e -> {
            hideLoadingDialog();
            T.show("获取失败");
        }));
    }

    @Override
    boolean isRange(double lat, double lng, double lat1, double lng1) {
        LatLng p1 = new LatLng(lat1,lng1);
        LatLng p2 = new LatLng(lat,lng);
        double distance = DistanceUtil.getDistance(p1,p2);
        //T.show("距离："+distance);
        L.d("签收距离："+distance);
        if (distance > 1000)
            return false;
        return true;
    }

    @Override
    void isCanSign(double lat, double lng) {
        showLoadingDialog(false);
        this.lat = lat;
        this.lng = lng;
        LocationUtils.getInstance(context).startOnce();
    }
    @Override
    void locationBack(BDLocation location){
        hideLoadingDialog();
        if (isRange(lat,lng,location.getLatitude(),location.getLongitude())){
            view.canSign();
        }else {
            view.canNotSign();
        }
    }
}
